/*
 * Copyright [2010] [Daniel H. Cavalcanti]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.collections;

import java.util.Collection;
import java.util.Comparator;

/**
 * A min heap implementation.
 *
 * @author Daniel Cavalcanti
 */
public class MinHeap<E>
    extends AbstractHeap<E>
    implements Heap<E> {

    public MinHeap() {
        super();
    }

    public MinHeap(Comparator<? super E> comparator) {
        super(comparator);
    }

    public MinHeap(Collection<E> collection) {
        super(collection);
    }

    public MinHeap(Collection<E> collection, Comparator<? super E> comparator) {
        super(collection, comparator);
    }

    @Override
    protected int getParentIndex(int i, int j)
    throws IndexOutOfBoundsException {

        if (i > size && j > size)
            throw new ArrayIndexOutOfBoundsException();
        if (i > size)
            return j;
        if (j > size)
            return i;

        if (comparator != null) {
            return comparator.compare(heap[i], heap[j]) < 0 ? i : j;
        } else {
            return ((Comparable<? super E>) heap[i]).compareTo(heap[j]) < 0 ? i : j;
        }

    }

}
